<?php
namespace app\api\logic;

class WeixinGzh extends Base {
    protected $isonlyopenid;    ##是否静默授权
    protected $notifyUrl;       ##微信支付回调URL
    protected $timeStamp;       ##当前时间戳
    protected $nonce;           ##随机数
    protected $accessKey;       ##入口验证KEY

    function __construct($appid = '', $secret = '', $isonlyopenid = false)     {
        $this->accessKey = config('custom.accessKey');
        $this->timeStamp = time();
        $this->nonce = mt_rand(10000, 99999);
        $this->isonlyopenid = $isonlyopenid;
        $this->notifyUrl = 'http://api.wei-yong.com/wx_notify';
    }

    /**
     * 微信支付参数配置 - 调用支付时调用
     * @param number $admin_id      客户ID
     * @param string $type          类型 - 默认为小程序: applet，公众号: gzh
     */
    public function wxPayConfig($admin_id) {
        $field = 'id, appid, secret, pay_mchid, pay_key, gzh_appid, gzh_secret';
        $res = db('customer')->where(['id' => $admin_id])->field($field)->find();

        if (!$res) {
            err('', 'ACCOUNT NULL');
        }
                
        // 公众号和小程序使用同一个商户
        $pay_mchid = $res['pay_mchid'];
        $pay_secret = $res['pay_key'];
        $appid = $res['gzh_appid'];
        $secret = $res['gzh_secret'];

        define('CUS_WX_APPID', $appid);
        define('CUS_WX_APPSECRET', $secret);
        define('CUS_WX_MCHID', $pay_mchid);
        define('CUS_WX_KEY', $pay_secret);
        define('CUS_WX_SSLCERT', VENDOR_PATH . 'Wxpay/cert/' . $res['id'] . '_cert.pem');   // ../cert/apiclient_cert.pem
        define('CUS_WX_SSLKEY', VENDOR_PATH . 'Wxpay/cert/' . $res['id'] . '_key.pem');    // ../cert/apiclient_key.pem
    }


    /**
     * 公众号微信授权登陆
     */
    public function login () {
        $appid = input ('get.appid');
    
        if (empty($appid)) {
            err('', '缺少参数');
        }
    
        // 测试 - 清除sessoin
        //session('gzh_userinfo', null);
    
        // 数据保存在session，不用每次都去请求
        if (session('?gzh_userinfo')) {
            $userinfo = session('gzh_userinfo');
        } else {
            // 获取微信code
            if (! input ('code')) {
                $redirect_uri = "http://api.wei-yong.com/api/weixin/zghWxLogin?appid=$appid";
                $this->_getWeixinCode ($appid, $redirect_uri);
                // 已经退出
            }
    
            // 查询客户ID是否存在
            $info = db ('customer')->where (['gzh_appid'=>$appid])
                ->field ('id, secret, gzh_appid, gzh_secret, gzh_access_token, gzh_access_token_expires, gzh_redirect_uri')
                ->find ();
    
            if (! $info) {
                err ('', 'PARAM ERROR');
            }
    
            // 根据code，交换userinfo
            $code = input ('code');
            $userinfo = $this->_getWeixinUserInfo ($code, $info['gzh_appid'], $info['gzh_secret']);
    
            // 查询用户是否创建
            $user = db ('user')->where (['openid' => $userinfo['openid']])->find ();
    
            // 创建用户
            if (! $user) {
                $data['admin_id'] = $info['id'];
                $data['openid'] = $userinfo['openid'];
                $data['nickname'] = removeEmoji ($userinfo['nickname']);
                $data['avatarurl'] = $userinfo['headimgurl'];
                $data['country'] = $userinfo['country'];
                $data['province'] = $userinfo['province'];
                $data['city'] = $userinfo['city'];
                $data['gender'] = $userinfo['sex'];
                $data['language'] = $userinfo['language'];
                $data['create_time'] = $this->timeStamp;
                $id = $user['id'] = db ('user')->insertGetId ($data);
            }
    
            $mstr = accessEncrypt($info['id'], $user['id'], $this->timeStamp, $info['secret'], $this->accessKey);
    
            $userinfo['mstr'] = $mstr;
            $userinfo['gzh_redirect_uri'] = $info['gzh_redirect_uri'];
    
            // 授权和mstr保存到session，减少重复访问数据库
            session('gzh_userinfo', $userinfo);
        }
    
        // 数据拼接用于前端获取
        $str = "";
        foreach ($userinfo as $key => $value) {
            if (is_string($value)) {
                $str .= $key . '=' . $value . '&';
            }
        }
    
        $str = rtrim($str, '&');
        $str = urlencode($str);
    
        // 跳转到指定页面
        $this->redirect($userinfo['gzh_redirect_uri'] . "?$str");
        exit ();
    }
    
    /**
     * 重定向获取微信用户code
     * 
     * @param string $appid         微信appid
     * @param string $redirect_uri  跳转url
     */
    public function _getWeixinCode ($appid, $redirect_uri)
    {
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
        $url .= 'appid=' . $appid;
        $url .= '&redirect_uri=' . urlencode ($redirect_uri);
        $url .= '&response_type=code';
        if (0) {
            $url .= '&scope=snsapi_base';
        } else {
            $url .= '&scope=snsapi_userinfo';
        }
        $url .= '&state=STATE#wechat_redirect';
    
        header ('location:' . $url);
        //print_r($url);
        exit ();
    }
    
    /**
     * 根据用户code获取用户信息
     * @param string $code      微信返回code
     * @param string $appid     微信appid
     * @param string $secret    微信secret
     */
    public function _getWeixinUserInfo ($code, $appid, $secret)
    {
        $rs = file_get_contents ('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . 
                                        '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code');
        
        $arr = json_decode ($rs, true);
        if (! empty ($arr['openid'])) {
            session ('openid', $arr['openid']);
        }
    
        if (! isset ($arr['access_token'])) {
            dump ($arr);
            die ();
        }
    
        $rs1 = file_get_contents ('https://api.weixin.qq.com/sns/userinfo?access_token=' . $arr['access_token'] . 
                                        '&openid=' . $arr['openid'] . '&lang=zh_CN');
        
        $userinfo = json_decode ($rs1, true);
        return $userinfo;
    }
    
    /**
     * 对外返回access_token、ticket、过期时间
     * 
     * @param string $appid     公众号appid
     * @return json
     */
    public function accessTokenReturn()
    {
        $appid = input ('get.appid');
    
        if (empty($appid)) {
            err('', '缺少参数');
        }
    
        $res = db ('customer')->where ("gzh_appid = '$appid'")
            ->field ('id, gzh_appid, gzh_secret, gzh_access_token, gzh_access_token_expires, gzh_ticket')
            ->find ();
    
        if (!$res) {
            err('', 'APPID错误');
        }
    
        $access = $this->gzhGetAccessToken($res);
        suc($access, '成功');
    }
    
    /**
     * 获取公众号的access_token
     * 
     * @param number $id
     * @param string $gzh_appid
     * @param string $gzh_secret
     * @param string $gzh_access_token
     * @param string $gzh_access_token_expires
     * @param string $gzh_ticket
     * @return array
     */
    public function accessTokenCreate ($res)
    {
        $admin_id = $res['id'];
    
        if (! $res) {
            err ('', 'ACCESS TOKEN PARAM NULL');
        }
    
        // 不存在或者过期，就重新获取access token
        if (empty ($res['gzh_access_token']) or $res['gzh_access_token_expires'] < $this->timeStamp) {
            // 获取access token
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential' . '&appid=' . $res['gzh_appid'] . '&secret=' . $res['gzh_secret'];
    
            $getMess = file_get_contents ($url);
            $arr = json_decode ($getMess, true);
    
            if (isset ($arr['errcode'])) {
                err ($arr, 'access token');
            }
    
            // 获取ticket
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&' . 'access_token=' . $arr['access_token'];
            $resTicket = file_get_contents ($url);
            $ticket = json_decode ($resTicket, true);
    
            // 更新access_token
            $data = [ ];
            $data['gzh_access_token'] = $arr['access_token'];
            $data['gzh_access_token_expires'] = $this->timeStamp + $arr['expires_in'];
            $data['gzh_ticket'] = $ticket['ticket'];
    
            $result = db ('customer')->where ("id = $admin_id")->update ($data);
    
            return $data;
        }
    
        $data = [];
        $data['gzh_access_token'] = $res['gzh_access_token'];
        $data['gzh_access_token_expires'] = $res['gzh_access_token_expires'];
        $data['gzh_ticket'] = $res['gzh_ticket'];
        return $data;
    }

    ### START - 微信卡券功能
    
    /**
     * 学习视频：http://edu.csdn.net/course/detail/5331/97060?pre_view=1
     * 账号：QQ登陆
     *
     * 1. 先登陆用户的公众号创建卡券
     * 2. 调用cardUpgradeTOApplet方法把公众号卡券升级为小程序卡券
     * 3. 调用cardAdd方法创建卡券
     * 4. 前端调用cardSubmitCode方法把创建的卡券，提交给后台并保存在数据库
     */
    
    /**
     * 微信卡券 - 把公众号的卡券升级成小程序也可以使用的卡券
     * @param number $admin_id    客户ID
     * @param string $card_id     卡券ID，在公众号卡券可以看到  
     * @param string $app_name    公众号原始ID，在公众号可以看到
     * @param string $name        名称 
     * @param string $app_page    跳转到小程序的页面，默认为pages/index/index
     * 
     */
    public function cardUpgradeToApplet ($info)
    {
        $data = [
            'card_id' => $info['card_id'], 
            'gift' => [ 
                'base_info' => [ 
                    'custom_url_name' => $info['name'], 
                    'custom_url' => 'http://api.wei-yong.com/api/WeixinGzh/cardUpgradeToApplet', 
                    'custom_app_brand_user_name' => $info['app_name'], 
                    'custom_app_brand_pass' => $info['app_page'], 
                    'custom_url_sub_title' => '兑换券', 
                    'center_app_brand_pass' => $info['app_page'], 
                    'promotion_url_name' => $info['name'], 
                    'promotion_url' => 'https://www.wei-yong.com', 
                    'promotion_app_brand_user_name' => $info['app_name'], 
                    'promotion_app_brand_pass' => $info['app_page']
                ]
            ]
        ];
        
        // 获取access token
        $cus = db ('customer')->where (['id' => $info['admin_id']])->find ();
        $access = $this->accessTokenCreate ($cus);
        
        $url = "https://api.weixin.qq.com/card/update?access_token=" . $access['gzh_access_token'];
        
        $data = json_encode ($data);
        $res = curl ($url, $data, 'json');
        
        return $res;
    }
    
    // 领取卡券
    // card - 课程表卡卷id
    public function cardAdd ()
    {
        $post = request ()->only (['card'], 'post');
    
        if (empty ($post['card'])) {
            err ('', '卡劵码不能为空');
        }
    
        $card_id = $post['card']; // 这个应该是前端传过来的参数
        $access_token = $this->gzhGetAccessToken ($this->accessData);
        $ticket = $this->cardGetTicket ($this->accessData);
        $data = [ ];
        $data['api_ticket'] = $ticket;
        $data['card_id'] = $card_id;
        $data['timestamp'] = $this->timeStamp;
        $data['nonce_str'] = getRandStr ('32');
        $data['openid'] = $this->logic->getOpenid ($this->accessData['uid']);
    
        asort ($data, SORT_STRING);
    
        $str = '';
        foreach ($data as $value) {
            $str .= $value;
        }
    
        $data['signature'] = sha1 ($str);
        $data['code'] = '';
        // $data['openid'] = '';
    
    
        suc ($data);
    }
    
    /**
     * 上传 - 增加卡券的code，并保存在数据库
     *
     * @param string $encrypt_code
     *            券加密字符串，解密后得到卡券ID
     * @param string $card_id
     *            微信卡券唯一标识ID
     * @return json
     */
    public function cardSubmitCode ()
    {
        $post = request ()->only ([
            'encrypt_code',
            'card_id'
        ], 'post');
    
        if (empty ($post['encrypt_code']) or empty ($post['card_id'])) {
            err ('', '参数错误');
        }
    
        $access_token = $this->gzhGetAccessToken ($this->accessData);
        $decrypt_msg = $this->cardDecryptCode ($post['encrypt_code'], $access_token['gzh_access_token']);
    
        $post['admin_id'] = $this->accessData['aid'];
        $post['user_id'] = $this->accessData['uid'];
        $post['code'] = $decrypt_msg['code'];
        $post['create_time'] = date ('Y-m-d H:i:s');
    
        try {
            $res = db ('card_wx')->insert ($post);
        } catch (\Exception $e) {
            err ('', '请勿重复提交');
        }
    
        if ($res <= 0) {
            err ();
        }
    
        suc ();
    }
    
    // 获取所有卡券
    public function cardGet ()
    {
        $post = request ()->only ([
            'page'
        ], 'post');
        $post['page'] = isset ($post['page']) ? $post['page'] : 0;
    
        $field = 'card_id, code, create_time';
        $where = [
            'admin_id' => $this->accessData['aid'],
            'user_id' => $this->accessData['uid']
        ];
        $res = db ('card_wx')->field ($field)
        ->where ($where)
        ->order ('create_time desc')
        ->limit ($post['page'], $this->page)
        ->select ();
    
        if (! $res) {
            err ('', '无数据');
        }
    
        suc ($res);
    }
    
    // 打开卡券
    public function cardOpen ()
    {
        $field = 'card_id, code, create_time';
        $where = [
            'admin_id' => $this->accessData['aid'],
            'user_id' => $this->accessData['uid']
        ];
        $res = db ('card_wx')->field ($field)
        ->where ($where)
        ->order ('create_time desc')
        ->select ();
    
        if (! $res) {
            err ('', '无数据');
        }
    
        suc ($res);
    }
    
    // 获取卡券的ticket
    public function cardGetTicket ($res)
    {
        $admin_id = $res['admin_id'];
    
        if (! $res) {
            err ('', 'ticket param null');
        }
    
        // 不存在或者过期，就重新获取
        if (empty ($res['ticket_card']) or $res['ticket_card_expires'] < $this->timeStamp) {
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=wx_card' . '&access_token=' . $res['gzh_access_token'];
    
            $res = useCurl ($url, '', '', '', 'get');
            $arr = json_decode ($res, true);
    
            if ($arr['errcode'] > 0) {
                err ($arr, 'ticket');
            }
    
            // 更新access_token
            $data = [ ];
            $data['ticket_card'] = $arr['ticket'];
            $data['ticket_card_expires'] = $this->timeStamp + $arr['expires_in'];
    
            $result = db ('customer')->where ([
                'id' => $admin_id
            ])->update ($data);
    
            return $data['ticket_card'];
        }
    
        return $res['ticket_card'];
    }
    
    // 解码加密的卡券code
    public function cardDecryptCode ($encrypt_code, $access_token)
    {
        $url = "https://api.weixin.qq.com/card/code/decrypt?access_token=$access_token";
    
        $data = [ ];
        $data['encrypt_code'] = $encrypt_code;
        $data = json_encode ($data);
    
        $res = curl ($url, $data, 'json');
    
        $res = json_decode ($res, true);
        // dump($res);die;
        if ($res['errcode'] > 0) {
            err ($res, 'card decrypt code');
        }
    
        return $res;
    }
    
    # END - 微信卡券功能
    
    
    /**
     * 公众号支付
     * @param unknown $dbInfo
     * @param array $payInfo
     */
    public function unifiedOrderGzh($dbInfo, $payInfo = [])
    {
        # 金额不能为空 - 为空会导致签名失败
        if ($dbInfo['amount'] <= 0) {
            err('', 'AMOUNT NULL');
        }
    
        # 引入配置参数
        self::wxPayConfig($dbInfo['admin_id'], 'gzh');
    
        require_once VENDOR_PATH . 'Wxpay/lib/WxPay.Api.php';
        require_once VENDOR_PATH . 'Wxpay/example/log.php';
        require_once VENDOR_PATH . 'Wxpay/example/WxPay.JsApiPay.php';
    
        # 获取openid
        $openid = $this->getOpenid($dbInfo['user_id']);
    
        # 订单号处理
        $orderId = $dbInfo['out_trade_no'];
    
        # 用于判断客户
        $attach = base64_encode("id={$dbInfo['admin_id']}");
    
        # 统一下单
        $tools = new \JsApiPay();
        //$openId = $tools->GetOpenid();
    
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        //商品描述
        $input->SetBody($dbInfo['subject']);
        //商户订单号
        $input->SetOut_trade_no($orderId);
        //总金额
        $input->SetTotal_fee($dbInfo['amount'] * 100);             // 计算总价 - 单位为分
        //通知地址
        $input->SetNotify_url($this->notifyUrl);
        $input->SetAttach($attach);                                // 自定义参数
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        //$input->SetGoods_tag("");
        //交易类型
        $input->SetTrade_type("JSAPI");
        //用户标识
        $input->SetOpenid($openid);
    
        //dump($input);die;
        //=========步骤3：使用jsapi调起支付============
        $jsApiParameters = \WxPayApi::unifiedOrder($input);
    
        if ($jsApiParameters['return_code'] == 'FAIL') {
            err('', $jsApiParameters['return_msg']);
        }
    
        if ($jsApiParameters['result_code'] == 'FAIL') {
            err($jsApiParameters, '微信创建订单失败');
        }
    
        # 订单信息写入数据库 - 未付款的订单不需要再创建订单数据
        # 订单信息写入数据库 - 未付款的订单不需要再创建订单数据
        if (!isset($payInfo['not_create_order'])) {
            $dbInfo['type'] = isset($dbInfo['type']) ? $dbInfo['type'] : 2;  // 1：货到付款，2：微信支付，3：支付宝支付;
            $dbInfo['openid'] = $openid;
            $dbInfo['out_trade_no'] = $orderId;
            $dbInfo['message'] = isset($dbInfo['message']) ? $dbInfo['message'] : ' ';
            $dbInfo['time_start'] = $input->GetTime_start();
            $dbInfo['time_expire'] = $input->GetTime_expire();
            $dbInfo['request_mess'] = json_encode($dbInfo);
            $dbInfo['time_start'] = time();
            db('order')->insert($dbInfo);
        }
    
        $editAddress = $tools->GetJsApiParameters($jsApiParameters);
        return $editAddress;
    }
    
    /**
     * 创建二维码
     * 参考：https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542
     * @param string $scene_id      场景值ID，临时二维码时为32位非0整型，永久二维码时最大值为100000（目前参数只支持1--100000）
     * @param string $scene_str     场景值ID（字符串形式的ID），字符串类型，长度限制为1到64
     * @return string
     */
    public function getGzhRqcode($scene_str)
    {
        $token = $this->gzhGetAccessToken();
        //$access_token = 'I66Tj48X0GgCYb72BxnvmMm_gw3qc5JYkjcXZilGy_XBMSybMF5XVRRgt6sup4GCreKs3HTa8TSN1KksMqstZaczqDMdUSGwOYHLDsb1d75B9mmTczby4bxTXJgbcCqKQPXcACATSA';
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $token['access_token'];
    
        $data = [];
        $data['action_name'] = 'QR_LIMIT_STR_SCENE';
        $data['action_info'] = ['scene' => ['scene_str' => $scene_str]];
        $data = json_encode($data);
        $res = curl($url, $data, 'json');
        $res = json_decode($res, true);
        $filename = $scene_str . '.jpg';
        return $this->getGzhRqcodeForever($res['ticket'], $filename);
    }
    
    /**
     * 根据二维码Ticket生成二维码图片
     * @param string $ticket
     * @return jpg
     */
    public function getGzhRqcodeForever($ticket, $filename)
    {
        $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=$ticket";
        $res = file_get_contents($url);
        $root = ROOT_PATH . 'public' . DS;
        $uploads = 'uploads' . DS;
    
        // 下载二维码到指定的路径
        file_put_contents($root . $uploads . $filename, $res);
        return $uploads . $filename;
    }
    
    /**
     * 获取公众号的access_token
     */
    public function gzhGetAccessToken ()
    {
        $res = db('access')->where(['appid'=>$this->appid])->find();
    
        // 不存在或者过期，就重新获取access token
        if (empty ($res['access_token']) or $res['expires_in'] < $this->timeStamp) {
            // 获取access token
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential' . '&appid=' . $this->appid . '&secret=' . $this->secret;
    
            $getMess = file_get_contents ($url);
            $arr = json_decode ($getMess, true);
    
            if (isset ($arr['errcode'])) {
                err ($arr, 'access token');
            }
    
            // 获取ticket
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&' . 'access_token=' . $arr['access_token'];
            $resTicket = file_get_contents ($url);
            $ticket = json_decode ($resTicket, true);
    
            // 更新access_token
            $data = [ ];
            $data['access_token'] = $arr['access_token'];
            $data['expires_in'] = $this->timeStamp + $arr['expires_in'];
            $data['ticket'] = $ticket['ticket'];
    
            if(! $res) {
                $data['create_time'] = $this->timeStamp;
                $data['appid'] = $this->appid;
                db('access')->insert($data);
            } else {
                $result = db('access')->where(['appid' => $this->appid])->update($data);
            }
    
            return $data;
        }
    
        $data = [];
        $data['access_token'] = $res['access_token'];
        $data['expires_in'] = $res['expires_in'];
        $data['ticket'] = $res['ticket'];
        return $data;
    }
    
    /**
     * 接入微信公众平台开发 - 验证消息的确来自微信服务器
     *
     * 微信平台推送事件消息解码后的数据如下:
     {
     "ToUserName": "gh_f583d8e94862",
     "FromUserName": "oSckZwuQR71E5eZ6C4Si0JseuJDo",
     "CreateTime": "1503671425",
     "MsgType": "event",
     "Event": "SCAN",
     "EventKey": "1",
     "Ticket": "gQHd8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyZkVtVlFxOTljcDIxMDAwMGcwM1kAAgSFE6BZAwQAAAAA"
     }
     */
    public function checkSignature()
    {
        $token = $this->token;
        $encodingAesKey = $this->encodingAesKey;
        $appId = $this->appid;
    
        # 验证消息是否来自微信服务器
        if (empty ($GLOBALS['HTTP_RAW_POST_DATA'])) {
            //logWriteInFile('First', $_REQUEST);
            $post = request()->only(['signature', 'timestamp', 'nonce', 'echostr'], 'get');
            $post['token'] = $token;
            $this->checkWxToken($post);
            exit();
        }
    
        // XML数据
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        logWriteInFile('Rqcode', $xml);
    
        // URL带过来的数据
        $post = input('');
        logWriteInFile('Rqcode-request', $post);
    
        # 接收微信公众平台推送的消息
        require_once VENDOR_PATH . 'WxDecryptMsg/wxBizMsgCrypt.php';
    
        $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
    
        // 解码公众平台推送的消息
        $errCode = $pc->decryptMsg($post['msg_signature'], $post['timestamp'], $post['nonce'], $xml, $msg);
        logWriteInFile('Rqcode-msg', $msg);
    
        // 把解码后的XML转成数组
        $result = json_decode (json_encode (simplexml_load_string ($msg, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        logWriteInFile('Rqcode-array', $result);
    
        /**
         * 首次关注
         * {
         *      "ToUserName":"gh_97ea833243fc",
         *      "FromUserName":"oP8pm1g3z5WqwpzUi1OjXx-gFG_U",
         *      "CreateTime":"1504080994",
         *      "MsgType":"event",
         *      "Event":"subscribe",
         *      "EventKey":"qrscene_0101222552_1504081746",
         *      "Ticket":"gQHT8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyOEtjeU4tX2FkQ20xMDAwME0wN2MAAgQuc6ZZAwQAAAAA"
         * }
         *
         * 关注后扫描二维码
         * {
         *      "ToUserName":"gh_97ea833243fc",
         *      "FromUserName":"oP8pm1g3z5WqwpzUi1OjXx-gFG_U",
         *      "CreateTime":"1504081262",
         *      "MsgType":"event",
         *      "Event":"SCAN",
         *      "EventKey":"0101222552_1504081746",
         *      "Ticket":"gQHT8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyOEtjeU4tX2FkQ20xMDAwME0wN2MAAgQuc6ZZAwQAAAAA"
         * }
         *
         * EventKey为二维码参数
         */
        if ($result['Event'] == 'subscribe') {
            // 用户扫描关注公众号事件
            $content = '猛戳 - http://www.wei-yong.com';
            $this->sendReplyMsg($result['FromUserName'], $result['ToUserName'], 'text', $content);
        } elseif ($result['Event'] == 'SCAN') {
            // 用户扫描进入公众号事件
    
            $content = '猛戳 -> http://www.wei-yong.com';
            $this->sendReplyMsg($result['FromUserName'], $result['ToUserName'], 'text', $content);
        }
    }
    
    /**
     * 接入微信公众平台开发 - 验证消息的确来自微信服务器
     * 参考: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319
     *
     */
    public function checkWxToken($info)
    {
        $tmpArr = array($info['token'], $info['timestamp'], $info['nonce']);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
    
        if($tmpStr == $info['signature']) {
            echo $info['echostr'];
        } else {
            echo 1;
        }
    }
    
    /**
     * 自动回复消息 - https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140543
     *
     * @param string $toUserName        接收方帐号（收到的OpenID）
     * @param string $fromUserName      开发者微信号/公众号原始ID
     * @param string $msgType           消息类型 - text/
     * @param string $content           回复的消息内容（换行：在content中能够换行，微信客户端就支持换行显示）
     */
    public function sendReplyMsg($toUserName, $fromUserName, $msgType, $content)
    {
        require_once VENDOR_PATH . 'WxDecryptMsg/wxBizMsgCrypt.php';
    
        // 第三方发送消息给公众平台
        $encodingAesKey = $this->encodingAesKey;
        $token = $this->token;
        $timeStamp = $this->timeStamp;
        $nonce = getRandStr(10);
        $appId = $this->appid;
    
        $text = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            </xml>";
    
        $str = sprintf($text, $toUserName, $fromUserName, $timeStamp, $msgType, $content);
        echo $str;
        logWriteInFile('Rqcode-msg', ['a'=>$str]);
    }
}